package com.boarsoft.boar.batch.action;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.batch.bean.BatchSchedule;
import com.boarsoft.boar.batch.quartz.QuartzSchedulerMonitor;
import com.boarsoft.boar.batch.service.BatchScheduler;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;

@RestController
@RequestMapping("/schedule")
public class BatchScheduleAction {
	private static final Logger log = LoggerFactory.getLogger(BatchScheduleAction.class);

	@Autowired
	private BatchScheduler scheduleBroker;

	@Autowired(required = false)
	@Qualifier("schedulerMonitor")
	private QuartzSchedulerMonitor monitor;

	@RequestMapping("/list.do")
	@Authorized(code = "batch.schedule.list")
	public ReplyInfo<Object> list(String catalog, String key, int pageNo, int pageSize) {
		try {
			List<BatchSchedule> aLt = scheduleBroker.list();
			if (Util.strIsNotEmpty(catalog)) {
				aLt = aLt.stream().filter(o -> o.getCatalog().equalsIgnoreCase(catalog)).collect(Collectors.toList());
			}
			if (Util.strIsNotEmpty(key)) {
				aLt = aLt.stream().filter(o -> o.getCode().toLowerCase().contains(key.toLowerCase()))
						.collect(Collectors.toList());
			}
			List<BatchSchedule> result = aLt.stream().skip((pageNo - 1) * pageSize).limit(pageSize)
					.collect(Collectors.toList());
			PagedResult<BatchSchedule> pr = new PagedResult<>(aLt.size(), result, pageNo, pageSize);
			return ReplyInfo.success(pr);
		} catch (Exception e) {
			log.error("Error on list batch schedule", e);
			return ReplyInfo.error(e.toString());
		}
	}

	@RequestMapping("/start.do")
	@Authorized(code = "batch.schedule.start")
	public ReplyInfo<Object> start() {
		try {
			if (monitor != null) {
				monitor.enableGroup();// 标记BatchLock.status为1-启用
			}
			scheduleBroker.start();
			return ReplyInfo.SUCCESS;
		} catch (Exception e) {
			log.error("Error on start quartz scheduler", e);
			return new ReplyInfo<Object>(Constants.ERROR_UNKNOWN);
		}
	}

	@RequestMapping("/stop.do")
	@Authorized(code = "batch.schedule.stop")
	public ReplyInfo<Object> stop() {
		try {
			if (monitor != null) {
				monitor.disableGroup();// 标记BatchLock.status为0-停用
			}
			scheduleBroker.stop();
			return ReplyInfo.SUCCESS;
		} catch (Exception e) {
			log.error("Error on stop quartz scheduler", e);
			return new ReplyInfo<Object>(Constants.ERROR_UNKNOWN);
		}
	}

	@RequestMapping("/delete.do")
	@Authorized(code = "batch.schedule.delete")
	public ReplyInfo<Object> delete(String id, String impl) {
		if (Util.strIsEmpty(id) || Util.strIsEmpty(impl)) {
			return new ReplyInfo<Object>(Constants.WARN_INVALID, "id,impl");
		}
		try {
			scheduleBroker.unschedule(id, impl);
			return ReplyInfo.SUCCESS;
		} catch (Exception e) {
			log.error("Error on stop quartz scheduler", e);
			return new ReplyInfo<Object>(Constants.ERROR_UNKNOWN);
		}
	}

	/**
	 * 返回定时器是否已启动（暂停模式）
	 */
	@RequestMapping("/status.do")
	public ReplyInfo<Object> status() {
		boolean b;
		if (monitor != null) {
			b = !monitor.groupStatus();
		} else {
			b = scheduleBroker.isStandByMode();
		}
		return new ReplyInfo<Object>(true, b ? "0" : "1");
	}
}